

/*JDBC简单查询*/


import java.sql.*;
import java.text.MessageFormat;

public class Demo01 {
    public static void main(String[] args) {
        //定义对象，方便之后释放资源
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet=null;

        try {
            //1.加载数据库厂商提供的驱动，MYSQL的JAR包就和JAVA环境建立了关系
            Class.forName("com.mysql.cj.jbdc.Driver");
            //2.建立数据库链接
            connection=DriverManager.getConnection("","root","123456");//url:标识数据库在哪的字符串
            //3.创建Statement对象（专门用来发送sql语句
            statement = connection.createStatement();
            //4.定义sql语句
            String sql="select id,name,sno,age,gender,enroll_date,class_id from student";//生产中不用*查询
            //5.执行sql,获取结果集
            resultSet = statement.executeQuery(sql);
            //6.遍历结果集，获取数据行（多行记录，一行一行地遍历
            while(resultSet.next()){//resultSet.next()返回一个boolean值，true表示有下一条记录
                //每进入一次循环，标识读取了一行数据
                //获取ID列的值,根据列的数据类型调用不同的方法
                long id = resultSet.getLong(1);
                //依次获取其他列的值
                String name = resultSet.getString(2);
                String sno = resultSet.getString(3);
                int age = resultSet.getInt(4);
                boolean gender = resultSet.getBoolean(5);
                Date enroll_date = resultSet.getDate(6);
                long class_id = resultSet.getLong(7);
                //打印结果
                System.out.println(MessageFormat.format("学生编号={0}，姓名={1}，学号={2}，年龄={3}，"+
                        "性别={4}，入学时间={5}，班级编号={6}",id,name,sno,age,gender,enroll_date,class_id));//使用占位符输出
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {//依次释放资源
            if(resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if(statement!=null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
